#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Zhangcl
from core.log_write import Log_wirite
from core import interactive
import sys
import traceback
import datetime
import paramiko
class Login_in(object):
    def __init__(self, user_id, bindhost_use):
        self.user_id = user_id
        self.bindhost_use = bindhost_use

    def login_start(self):
        try:
            client = paramiko.SSHClient()  # 创建SSH对象
            client.set_missing_host_key_policy(paramiko.WarningPolicy())
            print('*** Connecting %s...' % self.bindhost_use.host.ip_addr)
            client.connect(self.bindhost_use.host.ip_addr,
                           self.bindhost_use.host.port,
                           self.bindhost_use.remoteuser.username,
                           self.bindhost_use.remoteuser.password,
                           timeout=30)  # 根据传输进来的主机信息连接主机
            chan = client.invoke_shell()
            print(repr(client.get_transport()))
            print('*** Here we go!\n')
            cmd = 'login'
            date = datetime.datetime.now()
            log_obj = Log_wirite(self.user_id, self.bindhost_use.id, cmd, date)  # 登录成功时会记录一条登录日志
            log_obj.log_recording()
            interactive.interactive_shell(chan, self.user_id, self.bindhost_use)  # 进入交互
            chan.close()
            client.close()
        except Exception as e:
            print('*** Caught exception: %s: %s' % (e.__class__, e))
            traceback.print_exc()
            try:
                client.close()
            except:
                pass
            sys.exit(1)


